package com.clouds.wms.filter;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.clouds.wms.util.RequestHelper;
import com.clouds.wms.util.SpObserver;

public class DataSourceFilter extends HandlerInterceptorAdapter {

	//拦截地址
	private String[] dsInteceptorUrls;
	
	public String[] getDsInteceptorUrls() {
		return dsInteceptorUrls;
	}

	public void setDsInteceptorUrls(String[] dsInteceptorUrls) {
		this.dsInteceptorUrls = dsInteceptorUrls;
	}

	
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		
		//获取请求地址
		String uri=request.getRequestURI();	
		String ctx=request.getContextPath();		
		//去掉项目名称
		uri=uri.replaceFirst(ctx, "");			
		
		if(checkUriMatch(uri, dsInteceptorUrls))
		{
			
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			String dataSource = RequestHelper.getString(httpRequest, "dataSource");
			String dataSourceName = "htaDataSource";
			if(dataSource!=null &&dataSource.equals("HTA")){
				dataSourceName = "htaDataSource";
			}else if(dataSource!=null &&dataSource.equals("HXN")){
				dataSourceName = "hxnDataSource";
			}else if(dataSource!=null &&dataSource.equals("HXG")){
				dataSourceName = "hxgDataSource";
			}
			SpObserver.putSp("_"+dataSourceName);
		}
		
		return true;
		
		
		
	}
	
	/*
	 * 验证uri是否配置 配置的url规则（pattenUrls需符合java正则表达式的格式）
	 */
	private boolean checkUriMatch(String uri,String[] pattenUrls)
	{
		for(String pattenUrl:pattenUrls)
		{
			if(uri.matches(pattenUrl))
			{
				return true;
			}
		}
		
		return false;
	}
}
